classdef CBRPacketGenerator < ClockHandler
    properties (SetAccess = 'public', GetAccess = 'public')
        src_node = [];
        dest_node = [];
        
        packet_size_in_bytes = 0;
        data_rate_in_Kbps = 0;
        available_bytes_to_transmit = 0;
        is_disabled = false;
        
        packet_template = [];
    end
    
    methods
        function obj = CBRPacketGenerator(packet_template, data_rate_in_Kbps)
            if nargin > 0
                obj.is_disabled = false;
                obj.packet_template = packet_template;
                obj.packet_size_in_bytes = packet_template.size_in_bytes;
                obj.data_rate_in_Kbps = data_rate_in_Kbps;
                obj.available_bytes_to_transmit = 0;
            end
            
            %register on clock tick
            ck = ClockSingleton.instance();
            ck.register_for_clock_ticks(obj);
        end
        
        function disable(obj)
            obj.available_bytes_to_transmit = 0;
            obj.is_disabled = true;
        end
        
        function enable(obj)
            obj.available_bytes_to_transmit = 0;
            obj.is_disabled = false;
        end
        
        function clock_tick_handler(obj)
            params = ParamsSingleton.instance();
            if (obj.is_disabled)||(params.should_disable_all_traffic_generators)
                return;
            end
            %generate packets according to rate
            packets_manager = PacketsManager.instance();
            
            params = ParamsSingleton.instance();
            time_delta_in_msec = params.clock_tick_delta_in_msec;
            obj.available_bytes_to_transmit = obj.available_bytes_to_transmit + ((obj.data_rate_in_Kbps * (time_delta_in_msec/1000))*1024)/8;
            while obj.available_bytes_to_transmit > obj.packet_size_in_bytes
                obj.available_bytes_to_transmit = obj.available_bytes_to_transmit - obj.packet_size_in_bytes;    
                packets_manager.create_new_packet(obj.packet_template);
            end
        end

    end
end